package com.hj545.pl.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hj545.pl.DaoUtil;
import com.hj545.pl.bean.BackupVO;
import com.hj545.pl.bean.ConfVO;
import com.hj545.pl.bean.PropertieVO;
import com.hj545.pl.service.BizService;
import org.apache.commons.dbutils.DbUtils;

import java.io.File;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

public class DBServiceImpl extends BizService {

	public DBServiceImpl(ConfVO conf) {
		super(conf);
	}

	@Override
	public void execute() {
		Map<String, PropertieVO> kvMap = getBizData4db(super.conf);

		System.out.println(super.conf.getFilePath());
		writePropertiesFile(super.conf.getFilePath(), kvMap);
	}

	@Override
	public void backupDBData() {

		Connection conn = DaoUtil.getConn(conf.getIp(), conf.getPort(), conf.getDbname(), conf.getUsername(), conf.getPassword());
		// 遍历数据库中指定项目的环境变量和个人变量
		List<Map<String, Object>> list = DaoUtil.selectAllEvn(
				conn, conf.getProjectName());

		// 针对所有的环境和个人配置 进行数据导出
		for (Map<String, Object> map : list) {

			BackupVO backconf = new BackupVO(map.get("projectName").toString(),
					map.get("evnName").toString(), conf.getConfFilePath());

			Map<String, PropertieVO> kvMap = getBizData4db(conn,
					backconf.getProjectName(), backconf.getEvnName(), null);

			writeBackupFile(backconf, kvMap);
		}

	}

	private void writeBackupFile(BackupVO backconf, Map<String, PropertieVO> kvMap) {
		String json = JSON.toJSONString(kvMap);
		logger.info("\r\n{}", json);
//		kvMap = JSON.parseObject(json, new TypeReference<Map<String, PropertieVO>>(){});

		String backUpFileName = getBackupFileName(backconf);

		writePropertiesFile(backUpFileName, json);

	}

	private static String getBackupFileName(BackupVO backconf) {
		String fileName = backconf.getProjectName() + "_" + backconf.getEvnName() + ".bak";
		return backconf.getConfFilePath() + File.separator +  fileName;
	}

	private Map<String, PropertieVO> getBizData4db(ConfVO conf) {
		// get db data
		Connection conn = DaoUtil.getConn(conf.getIp(), conf.getPort(), conf.getDbname(), conf.getUsername(), conf.getPassword());
		Map<String, PropertieVO> kvMap = getBizData4db(conn, conf.getProjectName(), conf.getEvnName(), conf.getPcName());
		logger.debug("kvMap {}", kvMap);
		DbUtils.closeQuietly(conn);
		return kvMap;
	}

	private Map<String, PropertieVO> getBizData4db(Connection conn, String projectName, String evnName, String pcName) {
		List<PropertieVO> defaultList = DaoUtil.selectDefault(conn, projectName);
		logger.debug("defaultList {}", defaultList);
		List<PropertieVO> evnList = DaoUtil.selectEvn(conn, projectName, evnName);
		logger.debug("evnList {}", evnList);
		List<PropertieVO> pcList = DaoUtil.selectPc(conn, projectName, evnName, pcName);
		logger.debug("pcList {}", pcList);
		return replaceDbData(defaultList, evnList, pcList);
	}
}
